#include "opFastdfs.h"

bool COpFastDfs::IsFastDfsInitializated()
{
	return bInitializated;
}


COpFastDfs::COpFastDfs()
{
	bInitializated = false;

	FastDfsCfg = CAllConfigure::GetInstance().GetFastDfsConfiguration();

	if (fdfs_client_init(FastDfsCfg.cClientCfg.c_str()) != 0)
	{
		ERROR_MSG("init fdfs client failed !");
		return;
	}

	pTrackerServer = tracker_get_connection();
	if (pTrackerServer == nullptr)
	{
		ERROR_MSG("get tracker connection failed");
		fdfs_client_destroy();
		return;
	}


	bInitializated = true;
}

bool COpFastDfs::StoreDataToFastDFS(const SFastdfsData& storeData,  char* cUrldata, char* cGroupname)
{
	std::ostringstream SpliceURL;
	std::string cURL;
	char remote_filename[256];
	char file_id[128];

	memset(cGroupname, 0x00, FDFS_GROUP_NAME_MAX_LEN + 1);
	memset(remote_filename, 0x00, sizeof(remote_filename));
	memset(file_id, 0x00, sizeof(file_id));

	ConnectionInfo storageServer;

	if (tracker_query_storage_store(pTrackerServer,&storageServer, cGroupname, &store_path_index) != 0)
	{
		ERROR_MSG("get tracker connection failed");
		fdfs_client_destroy();
		return false;
	}

	const char* extensionName = nullptr;
	if (strlen(storeData.extensionName) > 0)
	{
		extensionName = storeData.extensionName;
	}

	int result = storage_upload_by_filebuff(pTrackerServer, &storageServer,
			store_path_index, storeData.pVoicemessage_data, storeData.usedLen, extensionName,
			nullptr, 0 , cGroupname, remote_filename);


	if (result != 0)
	{
		ERROR_MSG("group_name: " << cGroupname << " ip_addr: " << storageServer.ip_addr << " port: " << storageServer.port 
				<< "upload file failed ,error no: " << result << " error info: " << STRERROR(result));
		return false;
	}

	SpliceURL << FastDfsCfg.cDomain << cGroupname << "/" << remote_filename;
	cURL.assign(SpliceURL.str());
	memcpy(cUrldata, cURL.c_str(), cURL.length());

	return true;
}


COpFastDfs::~COpFastDfs()
{
	delete pTrackerServer;
	bInitializated = false;
}
